/**
	Copyright (c) 2009 ATTi 
	All rights reserved.
	Author: Michael Shu
	Date: 12/28/2009
*/

public with sharing class SelectContactController {
	public Boolean display{get; set;}
	public String additionalToEmail{get; set;}
	public String ccEmail{get; set;}
	public String bccEmail{get; set;}
	public String searchName {get; set;}
	public Boolean issobjNotEmpty {get; set;}
	public Boolean issobjEmpty {get; set;}
	public Boolean isemailNotEmpty {get; set;}
	public Boolean isemailEmpty {get; set;}
	public Boolean isContact{get; set;}
	public Boolean isUser{get; set;}
	public List<Contact> lContact{get; set;}
	public List<User> lUser{get; set;}
	public String selectedsobjtEmail {get; set;}
	public List<SelectOption> lsobjName{get; set;}
	public String selectedObjTypeName {get; set;}
	public List<SelectOption> lobjTypeName{get; set;}
	
	public SelectContactController(){
		display = true;
		lobjTypeName = new List<SelectOption>();
		lobjTypeName.add(new SelectOption('Contact', 'Contact'));
		lobjTypeName.add(new SelectOption('User', 'User'));
		selectedObjTypeName = lobjTypeName.get(0).getValue(); // default value
		isContact = false;
		isUser = false;
		
		selectedsobjtEmail = '';
		lsobjName = new List<SelectOption>();
		lContact = new List<Contact>();
		lUser = new List<User>();
		issobjNotEmpty = false;
		issobjEmpty = false;
		isemailNotEmpty = false;
		isemailEmpty = false;
		this.searchName = ApexPages.currentPage().getParameters().get('searchName'); // Get search Contact or User Name
        this.additionalToEmail = ApexPages.currentPage().getParameters().get('addEmail'); // Get search Contact Name
        this.ccEmail  = ApexPages.currentPage().getParameters().get('ccEmail'); // Get search Contact Name
        this.bccEmail = ApexPages.currentPage().getParameters().get('bccEmail'); // Get search Contact Name
        if(this.searchName != ''){
        	go();
        }
	}
	
	public String getTitle(){
		return 'Look Up ' + selectedObjTypeName;
	}
	
	public String getBlockTitle(){
		return selectedObjTypeName + ' Selector';
	}
		
	public void go(){
		if(searchName != null){
		  String likesearchName = searchName.trim();			  
		  try{
		  	if(likesearchName == '' || likesearchName == '*'){
		  		if(selectedObjTypeName == 'Contact'){
			  	    lContact= new List<Contact>([select c.Name, c.AccountId, c.Account.Name, c.Email, c.Ingenio_UserID__c, c.Ingenio_UserName__c  
				                                 from Contact c Order By c.Name limit 51]);
		  		}else if(selectedObjTypeName == 'User'){
			  	    lUser= new List<User>([select u.Name, u.Email, u.Ingenio_User_ID__c 
				                                 from User u where isActive = true Order By u.Name limit 51]);
		  		}
		  	}else{
		  		likesearchName ='%' + likesearchName.replaceAll('\\*', '%') + '%';		
		  		if(selectedObjTypeName == 'Contact'){
			  		lContact= new List<Contact>([select c.Name, c.AccountId, c.Account.Name, c.Email, c.Ingenio_UserID__c, c.Ingenio_UserName__c  
				                                 from Contact c where c.Name like :likesearchName Order By c.Name limit 51]);
		  		}else if(selectedObjTypeName == 'User'){
				    lUser= new List<User>([select u.Name, u.Email, u.Ingenio_User_ID__c 
					                             from User u where isActive = true and u.Name like :likesearchName Order By u.Name limit 51]);
		  		}
		  	}
			lsobjName = new List<SelectOption>();
			if(selectedObjTypeName == 'Contact' && !lContact.isEmpty()){
				for(Contact c : lContact){
					if(c.Email != null){
						lsobjName.add(new SelectOption(c.Email, '"' + c.Name + '" <' + c.Email + '>'));
					}
				}
			}else if(selectedObjTypeName == 'User' && !lUser.isEmpty()){
				for(User u : lUser){
					if(u.Email != null){
					    lsobjName.add(new SelectOption(u.Email, '"' + u.Name + '" <' + u.Email + '>'));
					}
				}
			}
		  }catch(NullPointerException nullex){
		  	// do nothing
		  }catch(Exception ex){
		  	System.debug(ex);
		  	addError(ex.getMessage());
		  }
		  resetDisplayList();
		}
	}
	
	private void resetDisplayList(){
		isemailNotEmpty = !lsobjName.isEmpty();
		isemailEmpty = lsobjName.isEmpty();
		
		issobjNotEmpty = true;
		issobjEmpty = false;
		if(selectedObjTypeName == 'Contact'){
			isContact = true;
			isUser = false;
			if(lContact.isEmpty()){
				issobjNotEmpty = false;
				issobjEmpty = true;
			}else if(lContact.size() == 51){
				addWarning('The search returned more than the maximum number of rows (50). Please refine your search criteria.');
			}
		}else if(selectedObjTypeName == 'User'){
			isContact = false;
			isUser = true;
			if(lUser.isEmpty()){
				issobjNotEmpty = false;
				issobjEmpty = true;
			}else if(lUser.size() == 51){
				addWarning('The search returned more than the maximum number of rows (50). Please refine your search criteria.');
			}
		}							
	}
	
	public void switchObjType(){
		if(selectedObjTypeName == 'Contact'){
			isContact = true;
			isUser = false;			
		}else if(selectedObjTypeName == 'User'){
			isContact = false;
			isUser = true;			
		}
		if(this.searchName != ''){
        	go();
        }		
	}
	
	public void addAdditionalTo(){
		if(additionalToEmail != '' && !additionalToEmail.endsWith(';')){
			additionalToEmail += ';';
		}
		additionalToEmail += selectedsobjtEmail;
	}

	public void addCC(){
		if(ccEmail != '' && !ccEmail.endsWith(';')){
			ccEmail += ';';
		}
		ccEmail += selectedsobjtEmail;
	}
	
	public void addBCC(){
		if(bccEmail != '' && !bccEmail.endsWith(';')){
			bccEmail += ';';
		}
		bccEmail += selectedsobjtEmail;
	}
	
	public static Contact[] getContacts(String toContactName){
		Contact[] ct = [select Id, Email from Contact where Name =: toContactName limit 2];
		return ct;
	}	
	
	public static Contact[] getContactVerify(String toContactId){
		Contact[] ct_verify = [select Name, Email from Contact where Id =: toContactId];
		return ct_verify;
	}
	
	public static Case getCase(String currentPageId){
		Case[] cs = [select Id, RecordTypeId, RecordType.Name, CaseNumber,Subject,SuppliedEmail,AccountId, ContactId, Contact.Name, OwnerId, Owner.Name,CSS_CustomerID__c  
		             from Case where Id =: currentPageId];
		if(cs.size() == 1){
			return cs[0];
		}
		return null;
	}
	
	public static EmailMessage getEmailMessage(String emailID){
		EmailMessage[] eMessage = [select BccAddress, CcAddress, FromAddress, hasAttachment, FromName, Incoming
		                                  , MessageDate, Id, Subject, TextBody, ToAddress, ParentId 
		                           from EmailMessage where id =: emailID];	
		if(eMessage.size() == 1){
			return eMessage[0];
		}
		return null;
	}
	
	public static List<Folder> getFolders(){
		return [Select f.Id, f.Name, f.Type from Folder f where f.Type = 'Email' Order By f.Name];	
	}
	
	public static List<EmailTemplate> getEmailTemplates(String fId){
		return [select e.Name, e.Id, e.TemplateType, e.Description from EmailTemplate e 
		        where e.FolderId =: fId and e.IsActive =: true Order By e.Name];
	}


    //    Method adds an Error message to the page
    private void addError(String errorMsg){         
        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,errorMsg);               
        ApexPages.addMessage(msg);
    } 
        
    //    Method adds an Warning message to the page
    private void addWarning(String warningMsg){         
        ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.WARNING,warningMsg);               
        ApexPages.addMessage(msg);
    }  
}